

const redis = require('../middleware/redis')
const jwt = require('jsonwebtoken')
const { nanoid } = require('nanoid')

const { getAccessToken, wxLogin } = require('../api/wx_login')
const { getNickName } = require('../api/nick')

const { createUser } = require('../service/user_service')

const { lackOfCode } = require('../error/errorType')

const { getUserInfo } = require('../service/user_service')

const {JWT_SECRET} = require('../config/config_dev')

class User {

    // 用户注册
    async register(ctx, next) {
        try {
            // 1.获取数据
            let { username, password } = ctx.request.body
            const { msg: nick_name } = await getNickName()
            let user_id = nanoid(32)
            // 连接数据库
            let res = await createUser({ user_id, username, password, nick_name })

            // 返回数据
            ctx.body = {
                code: 0,
                msg: '注册成功',
                result: {
                    user_id: res.user_id
                },  
                isSuccess: true
            }
        } catch (e) {
            console.error('用户注册失败', new Date(), e)
        }
    }

    // 账号密码登录
    async userLogin(ctx, next) {
        try {
            const { username } = ctx.request.body
            const {password,...result} = await getUserInfo({ username })
            const token=jwt.sign(result, JWT_SECRET, { expiresIn: '1m' })
            ctx.body = {
                code: 0,
                msg: '登录成功',
                result:{
                    token
                },
                isSuccess: true   
            }
        } catch (e) {
            console.error('用户登录失败', new Date(), e)
        }
    }

    // 微信小程序快捷登录
    async wxLogin(ctx, next) {
        const { code } = ctx.request.body
        if (!code) {
            ctx.app.emit('error', lackOfCode, ctx)
            return
        }
        // 看看微信token是否过期，过期就重新获取
        let token = await redis.get('wx_access_token')
        if (!token) {
            let res = await getAccessToken()
            if (res.access_token) {
                await redis.set('wx_access_token', res.access_token, 'EX', 7000)
                token = res.access_token
            } else {
                console.error('获取微信token失败', new Date())
                return
            }
        }
        try {
            const res = await wxLogin({ token, code })
            console.log(2222222, res);

        } catch (e) {
            console.error('微信小程序登录失败', new Date(), e)
        }
    }

    
}

module.exports = new User()